#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import sys
import web
import Umpweb
from Umpweb.base import session, _
from Umpweb.common.utils import local_exec
from Umpweb.common import utils, config
from Umpweb.db import api as db_api
from Umpweb.base import session, _, render_jinja


reload(sys)
sys.setdefaultencoding('utf-8')
render = render_jinja('static/templates/sysconfig', encoding='utf-8',)

class Base:
    def __init__(self):
        self.webpath = os.path.dirname(os.path.realpath(Umpweb.__file__))
        self.uiconf = config.cfgPath


class Config(Base):
    def GET(self):
        reload(config)
        expired_time = config.expired_time
        return render.config(expired_time = expired_time)


class SetExpiredTime(Base):
    def POST(self):
        web.header("Content-Type", "plain/text")
        params = web.input()
        expired_time = params.get('expired_time','10')
        if not os.path.isfile(self.uiconf):
            return "配置文件不存在"
        
        cat_cmd = "cat %s |grep expired_time "%(self.uiconf)
        out,err = local_exec(cat_cmd)
        if not out:
            set_cmd = "sed -i '2 aexpired_time = %s' %s"%(expired_time,self.uiconf)
        else:
            set_cmd = "sed -i '/expired_time/s/.*/expired_time = %s/' %s"%(expired_time,self.uiconf)

        out, err = local_exec(set_cmd)
        if err:
            return err

        return "SUCC"


class SysconfigList:

    def GET(self):
        return render.sysconfig_list()
    
class GridSysconfig:

    def GET(self):
        web_input = web.input()
        page, total, records, rows = \
                    utils.grid_rows_query(db_api.sysconfig_table, web_input, filters={})

        cells = ['id', 'module', 'key', 'value', 'decription', 'created_at', 'option']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class SysconfigUpdate:

    def GET(self):
        x = web.input()
        config_id = x.get('config_id') 
        sysconfig = db_api.sysconfig_get(config_id)
        return render.sysconfig_update(sysconfig=sysconfig) 

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'id': x.get('id').strip(),
            'value':x.value.strip(),
           }

        body = {"SysconfigUpdate": {'params': values}}
        return utils.web_return(body)
